package zpy.servlet.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Servlet implementation class CookieServlet
 */
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter writer = response.getWriter();
		Cookie[] cookies = request.getCookies();
		for(Cookie cookie:cookies){
			writer.println("cookie名-->"+cookie.getName());
			writer.println("cookie值-->"+ URLDecoder.decode(cookie.getValue(),"utf-8"));
			writer.println("过期时间-->"+cookie.getMaxAge());
			String comment = "";
			if (cookie.getComment()!=null) {
				comment = URLDecoder.decode(cookie.getComment(),"utf-8");
			}
			writer.println("提示信息-->"+comment);
			writer.println("域-->"+cookie.getDomain());
			writer.println("路径-->"+cookie.getPath());
		}
		Cookie cookie = new Cookie("password", URLEncoder.encode("天王盖地虎","utf-8"));
		cookie.setComment(URLEncoder.encode("口令","utf-8"));
		cookie.setMaxAge(2);
		cookie.setVersion(1);
		cookie.setDomain("localhost");
		cookie.setPath("/");
		cookie.setSecure(false);
		response.addCookie(cookie);
		
		HttpSession session = request.getSession();
		writer.println("SessionID"+session.getId());
		Integer count = (Integer) session.getAttribute("count");
		
		if (count == null) {
			count = 0;
		}
		count++;
		request.getSession().setAttribute("count", count);
		writer.println("页面刷新第"+count +"次");
		String contentPath = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() 
		+ ":" + request.getServerPort() + contentPath + "/";

		if (count%2 == 0) {
			response.setHeader("refresh", "1,url="+basePath+"CookieServlet");
		}else {
			
			response.setHeader("refresh", "3,url="+basePath+"CookieServlet");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
